//
//  RZConversationListViewController.m
//  RZIM
//
//  Created by reyzhang on 2021/8/3.
//

#import "RZConversationListViewController.h"
#import "RZIMClient.h"
#import "RZConversationCell.h"
#import "RZKitCommonDefine.h"


@interface RZConversationListViewController ()
@property (nonatomic, strong) dispatch_queue_t updateEventQueue;
@property (nonatomic, assign) BOOL isFirstLoad; //是否第一次加载
@end

@implementation RZConversationListViewController
#pragma mark - 初始化
/**
 初始化
 @displayConversationTypeArray  显示的会话类型
 @label 分组会话
 */
- (instancetype)initWithDisplayConversationTypes:(NSArray *)displayConversationTypeArray label:(NSInteger)label {
    self = [super init];
    if (self) {
        [self commonInit];
        self.displayConversationTypeArray = displayConversationTypeArray;
        self.label = label;
    }
    return self;
}


- (instancetype)initWithDisplayConversationTypes:(NSArray *)displayConversationTypeArray {
    return [self initWithDisplayConversationTypes:displayConversationTypeArray label:0];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    self.updateEventQueue = dispatch_queue_create("com.reyzhang.conversation.updateEventQueue", NULL);
    self.dataArray = @[].mutableCopy;
    self.isFirstLoad = YES;
}




#pragma mark - Life cycle

- (BOOL)isHairHead {
    if (@available(iOS 11.0, *)) {
        UIEdgeInsets safeAreaInsets = [UIApplication sharedApplication].delegate.window.safeAreaInsets;
        if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
            return safeAreaInsets.left > 0.0f;
        }else {
            return safeAreaInsets.bottom > 0.f;
        }
    }
    return NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.conversationListTableView];
    CGRect tableFrame = self.conversationListTableView.frame;
    
    CGFloat removeHeight = (!self.hidesBottomBarWhenPushed ? self.tabBarController.tabBar.frame.size.height : 0);
    tableFrame.size.height -= removeHeight;
    
    if (@available(iOS 11.0, *)) {
        CGFloat adjustTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top == 0 ? 0 : 20;
        CGFloat removeHeight = [self isHairHead]  ? 64 + adjustTop : 64;
        tableFrame.size.height -= removeHeight;
    } else {
        tableFrame.size.height -= 64;
    }
    self.conversationListTableView.frame = tableFrame;
    
    //cell 线
    CGFloat leftOffset = RZIMConfigCenter.ui.globalConversationPortraitLeftMargin + RZIMConfigCenter.ui.globalConversationPortraitSize.width + RZIMConfigCenter.ui.globalConversationPortraitRightMargin;
    if ([self.conversationListTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        self.conversationListTableView.separatorInset = UIEdgeInsetsMake(0, leftOffset, 0, 0);
    }
    if ([self.conversationListTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        self.conversationListTableView.layoutMargins = UIEdgeInsetsMake(0, leftOffset, 0, 0);
    }
    self.conversationListTableView.separatorColor = [UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1];
    
    //监听消息
    [self registerObserver];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.isConverstaionListAppear = YES;
//    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(loadData) object:nil];
//    [self performSelector:@selector(loadData) withObject:nil afterDelay:0.5];
    [self refreshConversationTableViewIfNeeded];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    self.isConverstaionListAppear = NO;
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (BOOL)shouldAutorotate
{
    return NO;
}

#pragma mark 加载数据
- (void)refreshConversationTableViewIfNeeded {
    if (self.isFirstLoad) [self startShowHUD];
    [[RZIMClient sharedClient] getConversationList:self.displayConversationTypeArray
                                             count:0
                                             label:self.label
                                           success:^(NSArray<RZConversation *> * _Nonnull dataSource) {
        if (self.isFirstLoad) [self endHideHUD];
        //勾子处理数据源
        self.dataArray = [self willReloadTableData:dataSource.mutableCopy];
        [self.conversationListTableView reloadData];
        [self updateEmptyConversationView];
        self.isFirstLoad = NO;
    } error:^(RZErrorCode nErrorCode,NSString *errorMessage) {
        if (self.isFirstLoad) [self endHideHUD];
        
    }];
}

@synthesize emptyConversationView = _emptyConversationView;
- (void)setEmptyConversationView:(UIView *)emptyConversationView {
    if (_emptyConversationView) {
        [_emptyConversationView removeFromSuperview];
    }
    _emptyConversationView = emptyConversationView;
    [self.conversationListTableView addSubview:_emptyConversationView];
}


- (void)updateEmptyConversationView {
    if (self.dataArray.count == 0) {
        self.emptyConversationView.hidden = NO;
    } else {
        self.emptyConversationView.hidden = YES;
    }
}

#pragma mark - Notification selector
- (void)registerObserver {

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(refreshConversationTableViewIfNeeded:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    

    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveMessageNotification:)
                                                 name:RZNotification_SocketRocketDidReceive
                                               object:nil];
}

/**
 重新进入前台后，强制刷新会话
 */
- (void)refreshConversationTableViewIfNeeded:(NSNotification *)notif {
    [self.dataArray removeAllObjects];
    [[RZIMClient sharedClient] getConversationList:self.displayConversationTypeArray
                                             count:0
                                             label:self.label
                                           success:^(NSArray<RZConversation *> * _Nonnull dataSource) {
        //勾子处理数据源
        NSMutableArray *array = [self willReloadTableData:dataSource.mutableCopy];
        if (array && array.count >0) {
            [self.dataArray addObjectsFromArray:array];
        }
        
        [self.conversationListTableView reloadData];
        [self updateEmptyConversationView];
        
    } error:^(RZErrorCode nErrorCode,NSString *errorMessage) {
    }];
}


/**
 接收到websocket消息后的处理
 */
- (void)didReceiveMessageNotification:(NSNotification *)notification {
    __weak typeof(self) weakSelf = self;
    dispatch_async(self.updateEventQueue, ^{
        [weakSelf updateConversationInfo:notification.object];
    });
}


- (void)updateConversationInfo:(RZMessage *)message {
    dispatch_main_async_safe(^{
        if (![message isKindOfClass:[RZMessage class]]) {
            return;
        }
        
        if (message.message.msgType < 100) { //对于非聊天消息，不做处理
            return;
        }
        
        //从会话列表中查找对应会话
        BOOL isFind = NO;
        for (int i = 0; i<self.dataArray.count; i++) {
            RZConversation *conversation = self.dataArray[i];
            if ([conversation.groupInfo.gid isEqualToString:message.gid]) {
                //处理会话
                isFind = YES;
                conversation.groupInfo.notReadCnt +=1;
                
                RZMessageInfo *msgInfo = [RZMessageInfo createWithSocketMessage:message];
                if (msgInfo) {
                    [conversation.messageList insertObject:msgInfo atIndex:0];
                }
                [self.conversationListTableView reloadData];
                break;
            }
        }
        
        //如果未找到，新增一个会话
        if (!isFind) {
//            RZConversation *conversation = [RZConversation createWithSocketMessage:message];
            [self refreshConversationTableViewIfNeeded];
        }
        
        //播放声音
        [[RZSystemSoundPlayer defaultPlayer] playSoundByMessage:message
                                                  completeBlock:^(BOOL complete) {
            if (complete) {
//                [self setExclusiveSoundPlayer];
            }
        }];
        
    });
}


#pragma mark - TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.dataArray.count) {
        RZConversationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RZConversationCell" forIndexPath:indexPath];
        cell.portraitStyle = RZIMConfigCenter.ui.globalConversationAvatarStyle;
        RZConversation *model = self.dataArray[indexPath.row];
        [cell setDataModel:model];
        //勾子
        [self willDisplayConversationTableCell:cell atIndexPath:indexPath];
        
        return cell;
    }
    return [[UITableViewCell alloc] initWithFrame:CGRectZero];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.dataArray.count) {
        return MAX([self rzConversationListTableView:tableView heightForRowAtIndexPath:indexPath],70);
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.dataArray.count) {
        RZConversation *model = self.dataArray[indexPath.row];
        [self onSelectedTableRow:tableView conversationModel:model atIndexPath:indexPath];
    }else {
        NSLog(@"超出现有数据 row:%ld , count:%ld",(long)indexPath.row,(long)self.dataArray.count);
    }
}

/*****************************************************************/
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}


- (void)tableView:(UITableView *)tableView
    commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
     forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        RZConversation *model = self.dataArray[indexPath.row];
        [[RZIMClient sharedClient] removeConversationWithTargetId:model.groupInfo.gid success:^{
            [self.dataArray removeObjectAtIndex:indexPath.row];
            [self.conversationListTableView deleteRowsAtIndexPaths:@[indexPath]
                                                  withRowAnimation:UITableViewRowAnimationFade];
        } error:^(RZErrorCode nErrorCode, NSString * _Nullable errorMessage) {
            
        }];
    }
    [self onDeletedTableRowAtIndexPath:indexPath];
    [self updateEmptyConversationView];
}

- (NSString *)tableView:(UITableView *)tableView
    titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

#pragma mark - 钩子

/**
 获取数据时，使用菊花组件
 */
- (void)startShowHUD {
}

/**
 数据获取后，隐藏菊花组件
 */
- (void)endHideHUD {
}

/**
 对外公开 获取会话后的数据拦截。 可进行数据加工处理
 */
- (NSMutableArray<RZConversation *> *)willReloadTableData:(NSMutableArray<RZConversation *> *)dataSource {
    return dataSource;
}

/**
 对外公开， cell已创建，用来配置cell样式
 */
- (void)willDisplayConversationTableCell:(RZConversationBaseCell *)cell atIndexPath:(NSIndexPath *)indexPath {
}

/**
 对外公开获取cell高度的方法
 */
- (CGFloat)rzConversationListTableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return RZIMConfigCenter.ui.globalConversationPortraitSize.height + 24;
}

/**
 对外公开，cell被选中后的事件处理
 */
- (void)onSelectedTableRow:(UITableView *)tableView
         conversationModel:(RZConversation *)model
               atIndexPath:(NSIndexPath *)indexPath {
    
}

/**
 对外公开，cell删除后的事件处理
 */
- (void)onDeletedTableRowAtIndexPath:(NSIndexPath *)indexPath {
}
#pragma mark Lazy

- (UITableView *)conversationListTableView {
    if (!_conversationListTableView) {
        _conversationListTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _conversationListTableView.backgroundColor = [UIColor whiteColor];
    
        _conversationListTableView.dataSource = self;
        _conversationListTableView.delegate = self;
        [_conversationListTableView registerClass:[RZConversationCell class] forCellReuseIdentifier:@"RZConversationCell"];
        _conversationListTableView.tableFooterView = [UIView new];
        
        if (@available(iOS 11.0, *)) {
            _conversationListTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
        }
        if (@available(iOS 15.0, *)) {
            _conversationListTableView.sectionHeaderTopPadding = 0;
        }
    }
    return _conversationListTableView;
}


- (UIView *)emptyConversationView {
    if (!_emptyConversationView) {
        _emptyConversationView = [[UIImageView alloc] initWithImage:RZResourceImage(@"no_message_img")];
        _emptyConversationView.center = self.conversationListTableView.center;
        CGRect emptyRect = _emptyConversationView.frame;
        emptyRect.origin.y -= 50;
        [_emptyConversationView setFrame:emptyRect];
        UILabel *emptyLabel =
            [[UILabel alloc] initWithFrame:CGRectMake(-10, _emptyConversationView.frame.size.height,
                                                      _emptyConversationView.frame.size.width + 20, 20)];
        emptyLabel.text = @"暂无消息";
        [emptyLabel setFont:[RZIMConfigCenter.font fontOfFourthLevel]];
        [emptyLabel setTextColor:[UIColor lightGrayColor]];
        emptyLabel.textAlignment = NSTextAlignmentCenter;
        [_emptyConversationView addSubview:emptyLabel];
        [self.conversationListTableView addSubview:_emptyConversationView];
    }
    return _emptyConversationView;
}
@end
